package com.ant.common.utils;

import java.net.URL;
import java.util.*;


/**
 * @author LB
 */
public class StringUtil {

    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }

    public static boolean objectIsEmpty(Object o) {
        if (Objects.isNull(o)) {
            return true;
        } else {
            return isEmpty(o.toString());
        }
    }

    public static boolean objectIsNotEmpty(Object o) {
        return !objectIsEmpty(o);
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static String listToString(List list, char separator) {
        return org.apache.commons.lang3.StringUtils.join(list.toArray(), separator);
    }

    public static String listToString(List list) {
        return listToString(list, ',');
    }

    public static <T> List<T> listRemoveNull(List<? extends T> oldList) {
        List<T> listTemp = new ArrayList();
        for (int i = 0; i < oldList.size(); i++) {
            if (oldList.get(i) != null) {
                listTemp.add(oldList.get(i));
            }
        }
        return listTemp;
    }

    public static <T> List<T> listRemoveNull2(List<? extends T> oldList) {
        oldList.removeAll(Collections.singleton(null));
        return (List<T>) oldList;
    }

    public static String StringAdd(String s, String appendStr, String split) {
        if (isNotEmpty(appendStr)) {
            if ("".equals(s)) {
                s = appendStr;
            } else {
                if (isNotEmpty(split)) {
                    s = s + split;
                }
                s = s + appendStr;
            }
        }
        return s;
    }

    public static String StringAdd(StringBuilder stringBuilder, String appendStr, String split) {
        if (isNotEmpty(appendStr)) {
            if (stringBuilder.length() == 0) {
                stringBuilder.append(appendStr);
            } else {
                if (isNotEmpty(split)) {
                    stringBuilder.append(split);
                }
                stringBuilder.append(appendStr);
            }
        }
        return stringBuilder.toString();
    }

    public static String StringAdd(String s, String appendStr) {
        return StringAdd(s, appendStr, ",");
    }

    public final static boolean isNumeric(String s) {
        if (s != null && !"".equals(s.trim())) {
            return s.matches("^[0-9]*$");
        } else {
            return false;
        }
    }

    /**
     * 下划线转小驼峰
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        char UNDERLINE = '_';

        if (param == null || isEmpty(param.trim())) {
            return "";
        }

        int len = param.length();

        //不包含下划线的，需要检查并转化为小写
        if (!param.contains("_")){
            boolean isUpper = false;
            boolean isLow = false;
            for (int i = 0; i < len; i++) {
                char c = param.charAt(i);
                if (Character.isLowerCase(c)){
                    isLow = true; //检查到小写
                }else
                if (Character.isUpperCase(c)){
                    isUpper = true; //检查到大写
                }else if (Character.isDigit(c)) {
                    isLow = true; //检查到数字就是小写
                }
            }

            //全部是大写的，需要转化为小写
            if (isUpper&&!isLow){
                return param.toLowerCase();
            }else {
                //有大写，有小写，直接返回原值
                return param;
            }
        }

        StringBuilder sb = new StringBuilder(len);
        boolean flag = false; // "_" 后转大写标志,默认字符前面没有"_"
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                flag = true;
                continue;   //标志设置为true,跳过
            } else {
                if (flag) {
                    //表示当前字符前面是"_" ,当前字符转大写
                    sb.append(Character.toUpperCase(param.charAt(i)));
                    flag = false;  //重置标识
                } else {
                    sb.append(Character.toLowerCase(param.charAt(i)));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 转化为大驼峰
     * @param str
     * @return
     */
    public static String camelToUpper(String str){
        if (isEmpty(str)){
            return "";
        }

        String first = str.substring(0, 1).toUpperCase();
        return first + str.substring(1, str.length());
    }

    public static String getFileExtension(URL extUrl) {
        //URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
        // String filename = "";
        //PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg

        String extension = "";
        String path = extUrl.getPath();
        //Checks for both forward and/or backslash
        //NOTE:**While backslashes are not supported in URL's
        //most browsers will autoreplace them with forward slashes
        //So technically if you're parsing an html page you could run into
        //a backslash , so i'm accounting for them here;
        String[] pathContents = path.split("[\\\\/]");
        if (pathContents != null) {
            int pathContentsLength = pathContents.length;
            //System.out.println("Path Contents Length: " + pathContentsLength);
//            for (int i = 0; i < pathContents.length; i++) {
//                System.out.println("Path " + i + ": " + pathContents[i]);
//            }
            //lastPart: s659629384_752969_4472.jpg
            String lastPart = pathContents[pathContentsLength - 1];
            String[] lastPartContents = lastPart.split("\\.");
            if (lastPartContents != null && lastPartContents.length > 1) {
                int lastPartContentLength = lastPartContents.length;
                // System.out.println("Last Part Length: " + lastPartContentLength);
                //filenames can contain . , so we assume everything before
                //the last . is the name, everything after the last . is the
                //extension
                String name = "";
                for (int i = 0; i < lastPartContentLength; i++) {
                    // System.out.println("Last Part " + i + ": "+ lastPartContents[i]);
                    if (i < (lastPartContents.length - 1)) {
                        name += lastPartContents[i];
                        if (i < (lastPartContentLength - 2)) {
                            name += ".";
                        }
                    }
                }
                extension = lastPartContents[lastPartContentLength - 1];
                // filename = name + "." +extension;
                // System.out.println("Name: " + name);
                // System.out.println("Extension: " + extension);
                // System.out.println("Filename: " + filename);
            }
        }
        return extension;
    }

    public static List<FastMap> listDistinct(List<FastMap> list) {
        final boolean isNull = null != list && list.size() > 0;
        List<FastMap> distinctList = new ArrayList<>();
        if (isNull) {
            Set<FastMap> set = new HashSet<FastMap>(list);
            distinctList.addAll(set);
        }
        return distinctList;
    }

    public static List<Integer> listIntDistinct(List<Integer> list) {
        final boolean isNull = null != list && list.size() > 0;
        List<Integer> distinctList = new ArrayList<>();
        if (isNull) {
            Set<Integer> set = new HashSet<Integer>(list);
            distinctList.addAll(set);
        }
        return distinctList;
    }


    public static Integer[] str2Int(String[] strings) {
        List<Integer> list = new ArrayList<>();
        for (String s : strings) {
            if (StringUtil.isEmpty(s)) {
                list.add(0);
            } else {
                list.add(Integer.valueOf(s));
            }
        }
        return list.toArray(new Integer[list.size()]);
    }

    public static List<String> str2List(String[] strings) {
        return new ArrayList<>(Arrays.asList(strings));
    }

    public static String changeFileName(String fileName, String changeName) {
        if (StringUtil.isEmpty(fileName)) {
            return "";
        }

        if (StringUtil.isEmpty(changeName)) {
            return fileName;
        }

        if (!fileName.contains(".")) {
            return fileName + changeName;
        }

        int position = fileName.lastIndexOf(".");
        String begin = fileName.substring(0, position);
        String end = fileName.substring(position);
        String nowTime = DateUtils.getNowTime2File();

        return begin + changeName + nowTime + end;
    }


    /**
     * 字符串转成List
     * @param str
     * @return
     */
    public static List<String> strToList(String str){
        List<String> list = new ArrayList<>();
        if (isEmpty(str)){
            return list;
        }

        if (!str.contains(",")){
            list.add(str);
        }else {
            String[] strings = str.split(",");
            list.addAll(Arrays.asList(strings));
        }
        return list;
    }


    /**
     * SQL对应JAVA的参数类型
     * @param sqlParam
     * @return
     */
    public static String formatSqlParam(String sqlParam){
        String paramater = "";
        switch (sqlParam){
            case "int":
            case "smallint":
                paramater = "Integer";
                break;
            case "bigint":
            case "timestamp":
                paramater = "Long";
                break;
            case "varchar":
            case "text":
            case "longblob":
                paramater = "String";
                break;
            case "datetime":
            case "date":
                paramater = "Date";
                break;
            case "decimal":
            case "double":
                paramater = "Double";
        }
        return paramater;
    }

}
